package com.zjt.smart.mvp.presenter.base;

import android.text.TextUtils;

import com.google.gson.JsonSyntaxException;
import com.zjt.smart.api.server.BaseServer;
import com.zjt.smart.mvp.view.LoadView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class OnlySuccessCallback extends BaseCallback {
    private static final String TAG = "OnlySuccessCallback";
    protected LoadView mLoadView;
    protected BaseServer mServer;

    public OnlySuccessCallback(LoadView loadView, BaseServer server) {
        mLoadView = loadView;
        mServer = server;
    }

    @Override
    public void onLoadCache(long cacheTime, String cachStr) {

    }

    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        if (call == null || call.isCanceled()){
            return;
        }
        if (!response.isSuccess()) {
            mLoadView.onFail(response.code(), "At " + TAG + "#onResponse-> " + response.errorBody().toString());
            return;
        }
        String jsonStr = "";
        try {
            jsonStr = response.body().string();
            JSONObject jsonObject = new JSONObject(jsonStr);
            if (!TextUtils.isEmpty(jsonStr)) {
                List<Boolean> list = new ArrayList<Boolean>();
                boolean success = jsonObject.getBoolean("success");
                list.add(success);
                mLoadView.onSuccess(list);
                return;
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            mLoadView.onFail(mServer.PARSE, "At " + TAG + "#onResponse-> Parse Error:"+jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
            mLoadView.onFail(mServer.SYNTAX, "At " + TAG + "#onResponse-> Can't Find Object.Because JSONNull");
        }
        mLoadView.onSuccess(null);
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        if (call == null || call.isCanceled()){
            return;
        }
        mLoadView.onFail(BaseServer.SYNTAX, "At " + TAG + "#onFailure-> " + t.toString());
    }
}
